package com.lagou.eud.filter;

import com.lagou.edu.service.TokenDubboService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Reference
    private TokenDubboService tokenDubboService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if ("GET".equals(request.getMethodValue())) {
            if (request.getPath().toString().startsWith("/api/code/")
                    || request.getPath().toString().startsWith("/api/user/")
            ) {
                return chain.filter(exchange);
            }
            HttpCookie token = request.getCookies().getFirst("token");

            if (token == null || StringUtils.isEmpty(token.getValue())) {
                // 跳转登录页面
                String redirectUrl = "/static/login.html";
                response.getHeaders().set(HttpHeaders.LOCATION, redirectUrl);
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                return response.setComplete();
            } else {
                // 通过token获取用户邮箱
                String email = tokenDubboService.findEmailByToken(token.getValue());
                if (StringUtils.isEmpty(email)) {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    String data = "该用户未注册，请先注册";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
